package es.ubu.ceudaaj.exercise.ud02.t04.l03;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Class for management of console menu.
 */
public class Menu {
	private static final String EXIT_KEY = "q";
	
	/**
	 * Prints an intro header for console menu.
	 */
	public static void printMenuHeader() {
		StringBuilder sb = new StringBuilder("AGENDA DE CONTACTOS")
			.append("\n--------------------")
			.append("\nLista de contactos:");
		System.out.println(sb);
	}

	/**
	 * Prints the main menu of options in console.
	 */
	public static void printMainMenu() {
		StringBuilder sb = new StringBuilder("--------------------")
			.append("\nMenu de opciones:")
			.append("\n\t1. Cargar contactos desde fichero XML")
			.append("\n\t2. Guardar contactos en fichero XML")
			.append("\n\t3. Crear nuevo contacto")
			.append("\n\t4. Ver detalle de contacto")
			.append("\n\t5. Editar contacto")
			.append("\n\t6. Eliminar contacto")
			.append("\n\t7. Buscar contactos por nombre")
			.append("\n\t8. Buscar contactos por cargo")
			.append("\n\t9. Buscar contactos por C. Postal")
			.append("\n\t" + EXIT_KEY + ". Salir")
			.append("\n--------------------")
			.append("\nSeleccione una opcion: ");
		System.out.print(sb);
	}
	
	/**
	 * Method used to wait for user confirmation on console.
	 * 
	 * To be called if we want the user to see some information before refreshing menu. 
	 * 
	 * @throws IOException
	 */
    public static void pause() throws IOException {
        System.out.print("Pulse Enter para continuar...");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    /**
     * Picks the option entered typed by the user in console.
     * 
     * If it detects pulsation of the exit key ('q' by default), it exits the program.
     * 
     * @return The number typed by the user as a menu selection.
     * @throws IOException
     */
    public static int readOptionFromConsole() throws IOException {
        String userInput = null;
        int selectedOption = -1;
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        userInput = br.readLine();
        try {
            if (userInput.equals(EXIT_KEY)) {
            	System.out.println("Aplicacion finalizada.");
                System.exit(0);
            }
            selectedOption = Integer.parseInt(userInput);
        } catch (NumberFormatException ex) {}
        return selectedOption;
    }

	public static String readStringFromConsole() throws IOException {
		InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
		return br.readLine();
	}
}
